package com.exercise.ThreadPool;

import org.junit.Test;

import java.util.concurrent.*;

public class ThreadPoolDemo {
    @Test
    public void test1() {
        //CPU核心数
        int coreCount = Runtime.getRuntime().availableProcessors();

        //手动创建线程池
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                coreCount, // 核心线程数
                coreCount * 2, // 最大线程数,CPU核心数的两倍
                60L, // 线程空闲时间
                TimeUnit.SECONDS, // 时间单位
                new ArrayBlockingQueue<>(100), //  任务队列,容量为100的有界
                Executors.defaultThreadFactory(), // 默认的线程工厂
                new ThreadPoolExecutor.CallerRunsPolicy() // 拒绝策略,由调用者执行
        );

        //使用线程池
        try{
            for (int i = 0; i < 200; i++) {
                final  int index = i;
                threadPoolExecutor.execute(()->{
                    try{
                        System.out.println(Thread.currentThread().getName()  + ":正在执行任务" + index);
                        Thread.sleep(1000);
                        System.out.println(Thread.currentThread().getName()  + ":任务" + index + "执行完毕");
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }
                });
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            threadPoolExecutor.shutdown();
        }
    }


    @Test
    public void test2(){
        //CPU核心数
        int coreCount = Runtime.getRuntime().availableProcessors();

        //手动创建线程池
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                coreCount, // 核心线程数
                coreCount * 2, // 最大线程数,CPU核心数的两倍
                60L, // 线程空闲时间
                TimeUnit.SECONDS, // 时间单位
                new ArrayBlockingQueue<>(100), //  任务队列,容量为100的有界
                Executors.defaultThreadFactory(), // 默认的线程工厂
                new ThreadPoolExecutor.CallerRunsPolicy() // 拒绝策略,由调用者执行
        );

        Future<String> future = threadPoolExecutor.submit(() -> {
            System.out.println(Thread.currentThread().getName() + " 正在执行有返回值的任务...");
            Thread.sleep(1000);
            return "任务完成";
        });
       try{
           String result = future.get(); //阻塞等待，直到获取结果
       }catch (InterruptedException | ExecutionException e){
           e.printStackTrace();
       }

    }

}
